package f.v4;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import f.FileOp;
import v4.text.TextJmConfig;

public class PK {

	private static final Mode THIS_MODE = null;
	
	private static enum Mode {
		encrypt, decrypt
	}
	
	private static String getPK(String res) {
		InputStream is = PK.class.getResourceAsStream(res);
		if(is!=null) {
			Reader fr = null;
			BufferedReader br = null;
			try {
				fr = new InputStreamReader(is, "UTF-8");
				br = new BufferedReader(fr);
				String line = null;
				StringBuilder sb = new StringBuilder();
				while((line=br.readLine())!=null) {
					sb.append(line);
				}
				return sb.toString();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} finally {
				try {
					if(br!=null) br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if(fr!=null) fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		//throw new RuntimeException("PK load fail");
		String pk = FileOp.pleaseInput("PK["+res+"]: ");
		return pk.trim();
	}
	
	public static void loadPK(TextJmConfig jmConfig) {
		try {
			TextZjm zjm = TextZjm.defaultZjm(jmConfig);
			if(THIS_MODE==Mode.encrypt) {
				String pk =  getPK("sy.k");
				jmConfig.setRSA_PUBLICKEY(null);
				jmConfig.setRSA_PRIVATEKEY(zjm.jm(pk));
			}else if(THIS_MODE==Mode.decrypt) {
				String pk = getPK("gy.k");
				jmConfig.setRSA_PUBLICKEY(zjm.jm(pk));
				jmConfig.setRSA_PRIVATEKEY(null);
			}else {
				String gy = getPK("gy.k");
				String sy = getPK("sy.k");
				if(gy.length()>0) {
					jmConfig.setRSA_PUBLICKEY(zjm.jm(gy));
				}else {
					jmConfig.setRSA_PUBLICKEY(null);
				}
				if(sy.length()>0) {
					jmConfig.setRSA_PRIVATEKEY(zjm.jm(sy));
				}else {
					jmConfig.setRSA_PRIVATEKEY(null);
				}
			}
		}catch (Exception e) {
			throw new RuntimeException("PK load fail");
		}
	}
	
	public static void main(String[] args) throws Exception {
		v4.text.RsaKit.createRsaKeyPair();
	}
	
}
